<template>
  <div class="container">
    <MySearch
      :father-search="value"
      v-model="value"
      placeholder="请输入搜索内容"
    />
    <div class="line"></div>
    <van-tabs v-model="active" class="tab-box" color="#39A9ED" line-width="70">
      <van-tab
        class="tab"
        v-for="item in tabs"
        :title="item.title"
        :key="item.type"
      ></van-tab>
    </van-tabs>
    <NewsItem :news="list[active]" />
  </div>
</template>

<script>
import { Tab, Tabs, Toast} from "vant";
import MySearch from "../components/Search.vue";
import NewsItem from "../components/NewsItem.vue";
import { requestTypeNews } from "@/http";
export default {
  name: "News",
  data() {
    return {
      value: "",
      active: 0,
      tabs: [
        {
          title: "国际新闻",
          type: 0,
        },
        {
          title: "国内新闻",
          type: 1,
        },
        {
          title: "农业新闻",
          type: 2,
        },
        {
          title: "扶贫新闻",
          type: 3,
        },
      ],
      list: [],
      type: ["guoji", "guonei", "nongye", "fupin"],
      guoji: [],
      guonei: [],
      nongye: [],
      fupin: [],
    };
  },
  mounted() {
    for (let i = 0; i < this.tabs.length; i++) {
      this.getTypeNews(this.tabs[i].type);
    }
    // 添加滚动条的监听事件
    window.addEventListener("scroll", this.onScroll);
  },
  beforeDestroy() {
    // 移除滚动条的监听事件
    window.removeEventListener("scroll", this.onScroll);
  },
  methods: {
    // 查找分类数据 每次10条
    getTypeNews(type) {
      requestTypeNews(type).then((res) => {
        // this.list[type] = res.detail
        this.$set(this.list, type, res.detail);
      });
    },
    // 监听滚动条滚动事件 当触底时查询新的10条数据
    onScroll() {
      const scrollTop = document.documentElement.scrollTop; //滚动高度
      const clientHeight = document.documentElement.clientHeight; // 可视区域/屏幕高度
      const scrollHeight = document.documentElement.scrollHeight; // 页面高度
      // If(滚动高度 + 可视区域  >= 页面高度){ do something}
      if (scrollTop + clientHeight + 3 >= scrollHeight) {
        Toast.loading({
          duration: 300,
          message: "加载中...",
          forbidClick: true,
        });
        // 触底加载事件
        this.onReachBottom();
      }
    },
    //触底加载事件
    onReachBottom() {
      requestTypeNews(this.active).then((res) => {
        const newArr = this.list[this.active].concat(res.detail);
        this.$set(this.list, this.active, newArr);
        console.log(this.list);
      });
    },
  },
  components: {
    [Tab.name]: Tab,
    [Tabs.name]: Tabs,
    [Toast.name]: Toast,
    MySearch,
    NewsItem,
  },
};
</script>

<style scoped>
.line {
  margin-top: 8px;
  margin-bottom: 8px;
  width: 100%;
  height: 1px;
  background-color: #f8f9f9;
}
</style>